from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.views import View
from web import models
from django.shortcuts import redirect
from django_redis import get_redis_connection
from django.conf import settings
import json
from utils.encrypt import uid
from alipay import AliPay
from alipay.utils import AliPayConfig
import datetime
from django.conf import settings
class IndexView(View):
    def get(self, request):
        return render(request, 'web/index.html')


class PriceView(View):
    '''
    价格套餐页面
    '''

    def get(self, request):
        policy_list = models.PricePolicy.objects.filter(category=2)
        return render(request, 'web/price.html', {'policy_list': policy_list})


class PaymentView(View):
    '''
    购物车页面
    '''

    def get(self, request, policy_id):
        policy_object = models.PricePolicy.objects.filter(id=policy_id, category=2).first()
        if not policy_object:
            return redirect('web:price')
        number = request.GET.get('number', '')
        if not number or not number.isdecimal():
            return redirect('web:price')
        number = int(number)
        if number < 1:
            return redirect('web:price')
        # 获取价格
        origin_price = number * policy_object.price
        # 之前购买的套餐
        balance = 0
        _object = None
        if request.tracer.price_policy.category == 2:
            # 找到之前的订单
            import datetime
            _object = models.Transaction.objects.filter(user=request.tracer.user, status=2).order_by('-id').first()
            total_timedelta = _object.end_datetime - _object.start_datetime
            balance_timedelta = _object.end_datetime - datetime.datetime.now()
            if total_timedelta.days == balance_timedelta.days:
                # 按照价值进行计算抵扣金额
                balance = _object.price_policy / total_timedelta.days * (balance_timedelta.days - 1)
            else:
                balance = _object.price_policy / total_timedelta.days * balance_timedelta.days
        if balance >= origin_price:
            return redirect('web/price')
        context = {
            'policy_id': policy_object.id,
            'number': number,
            'origin_price': origin_price,
            'balance': round(balance, 2),
            'total_price': origin_price - round(balance, 2)
        }

        #
        import json
        conn=get_redis_connection()
        key='payment_{}'.format(request.tracer.user.mobile_phone)
        conn.set(key,json.dumps(context),ex=60*30)
        context['policy_object'] = policy_object
        context['transaction'] = _object
        return render(request, 'web/payment.html', context)


class PayView(View):
    def get(self, request):
        conn = get_redis_connection()
        key = 'payment_{}'.format(request.tracer.user.mobile_phone)
        context_string = conn.get(key)
        #订单超时
        if not context_string:
            return redirect('web:price')
        import json
        from utils.encrypt import uid

        context=json.loads(str(context_string,encoding='utf8'))
        #1  在数据库中生成交易记录 订单 待支付
        order_id = uid(request.tracer.user.mobile_phone)
        total_price=context['total_price']
        models.Transaction.objects.create(
            status=1,
            order=order_id,
            user=request.tracer.user,
            price_policy_id=context['policy_id'],
            count=context['number'],
            price=context['total_price']
        )
        #2 跳转到支付宝进行支付

        subject = "测试订单"

        alipay = AliPay(
                appid=settings.ALI_APPID,
                app_notify_url=settings.ALI_NOTIFY_URL,  # 默认回调 url
                app_private_key_string=settings.ALI_PRI_KEY_PATH,
                # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
                alipay_public_key_string=settings.ALI_PUB_KEY_PATH,
                sign_type="RSA2",  # RSA 或者 RSA2
                debug=True,  # 默认 False
                verbose=True,  # 输出调试数据
                config=AliPayConfig(timeout=15)  # 可选，请求超时时间
            )
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=total_price,
            subject=subject,
            return_url=settings.ALI_RETURN_URL,#一般是get请求
            notify_url=settings.ALI_NOTIFY_URL  # 可选，不填则使用默认 notify url  是post请求 没有公网ip 收不到
        )
        # 跳转到支付宝的页面进行支付
        pay_url = "{}?{}".format(settings.ALI_GATEWAY, order_string)

        return redirect(pay_url)


class PayNotify(View):
    '''
    支付成功后触发的url  支付宝支付成功后会
    '''
    def get(self,request):
        '''
        判断支付成功
        页面跳转
        :param request:
        :return:
        '''
        alipay = AliPay(
            appid=settings.ALI_APPID,
            app_notify_url=settings.ALI_NOTIFY_URL,  # 默认回调 url
            app_private_key_string=settings.ALI_PRI_KEY_PATH,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=settings.ALI_PUB_KEY_PATH,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=True,  # 默认 False
            verbose=True,  # 输出调试数据
            config=AliPayConfig(timeout=15)  # 可选，请求超时时间
        )
        # params=request.GET.dict()
        # signature=params.pop('sign',None)
        # success = alipay.verify(params, signature)
        from urllib.parse import parse_qs
        body_str = request.body.decode('utf-8')
        post_data = parse_qs(body_str)
        post_dict = {}
        for k, v in post_data.items():
            post_dict[k] = v[0]

        sign = post_dict.pop('sign', None)
        status = alipay.verify(post_dict, sign)
        print(status)
        # if success and params["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
        #     print(success,'---',params)
        #     print("trade succeed")
        return HttpResponse('sss')
    def post(self,request):
        '''
        订单更新  model
        :param request:
        :return:
        '''

        '''
        from urllib.parse import parse_qs
        body_str = request.body.decode('utf-8')
        post_data = parse_qs(body_str)
        post_dict = {}
        for k, v in post_data.items():
            post_dict[k] = v[0]

        sign = post_dict.pop('sign', None)
        '''
        return HttpResponse('')